package com.weilive.platform.gate.servlet;

import org.jboss.netty.handler.codec.http.HttpRequest;
import org.jboss.netty.handler.codec.http.HttpResponse;
import org.springframework.stereotype.Service;

import com.weilive.core.netty.http.HttpServlet;
import com.weilive.core.utils.QueryStringDecoder;
import com.weilive.core.utils.RegexUtils;
import com.weilive.platform.cache.user.UserManager;
import com.weilive.platform.dao.user.mapper.UserTokenDO;

@Service
public class ResetPwdServlet extends HttpServlet {

	private final static String content = "<form action=\"/user/password/reset\" method=\"post\">"
			+ "<p>新密码: <input type=\"password\" name=\"password\" /></p>"
			+ "<p>确认密码: <input type=\"password\" name=\"confirm\" /></p>"
			+ "<input type=\"hidden\" name=\"token\" value=\"${token}\" />" + "<input type=\"submit\" value=\"提交\" />"
			+ "</form>";

	@Override
	public String getServletPath() {
		return "/user/password/reset";
	}

	@Override
	public HttpResponse processRequest(HttpRequest request) throws Exception {
		QueryStringDecoder decoder = decodeQueryString(request);
		String password = decoder.get("password");
		String confirm = decoder.get("confirm");
		if (password == null || RegexUtils.isPassword(password) == false) {
			return createXmlResponse("密码格式错误！");
		} else if (password.equals(confirm) == false) {
			return createXmlResponse("两次输入密码不一致！");
		}
		UserTokenDO token = UserManager.getUserToken(decoder.get("token"));
		if (token == null || token.getEdate().getTime() < System.currentTimeMillis()) {
			return createXmlResponse("Token不存在或者已过期！" + token);
		} else {
			UserManager.useUserToken(token);
			UserManager.setUserPassword(token.user_id, password);
			return createXmlResponse("密码重置成功！");
		}
	}
}
